package io.bsly.modules.app.controller;

import io.bsly.common.utils.FileUtil;
import io.bsly.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Slf4j
@Api(tags = "文件上传")
@RestController
@RequestMapping("app/upload")
public class UploadController {

    @Value("${bsly.upload-path}")
    private String uploadPath;
    private String folderName = "files";


    @ApiOperation(value = "文件上传" ,notes = "MultipartFile file")
    @PostMapping
    public R uploadImage(@RequestParam("file") @ApiParam  MultipartFile file){
        if (file.isEmpty()) {
            return R.error("文件为空");
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String fileName = uuid + "." + FileUtil.getExtensionName(file.getOriginalFilename());
        log.info("文件名 [{}]", fileName);
        try {
            String path = ResourceUtils.getURL(uploadPath).getPath() + "/" + folderName;
            File targetFile = new File(path, fileName);
            file.transferTo(targetFile);
            log.info("保存至[{}]", targetFile.getPath());
            return R.ok().put("path",folderName + "/" + fileName);
        } catch (Exception e) {
            log.error("文件上传失败", e);
           return R.error("文件上传失败");
        }
    }

}
